package org.example.springtest.exception;

import jakarta.validation.ConstraintViolationException;
import org.example.springtest.model.dto.responseMessage;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public responseMessage<?> handleValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        String errorMsg = bindingResult.getFieldError().getDefaultMessage();
        return responseMessage.error(400, errorMsg);
    }

    @ExceptionHandler(BindException.class)
    public responseMessage<?> handleBindException(BindException ex) {
        String errorMsg = ex.getFieldError().getDefaultMessage();
        return responseMessage.error(400, errorMsg);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public responseMessage<?> handleConstraintViolationException(ConstraintViolationException ex) {
        String errorMsg = ex.getConstraintViolations().iterator().next().getMessage();
        return responseMessage.error(400, errorMsg);
    }

    @ExceptionHandler(Exception.class)
    public responseMessage<?> handleOtherException(Exception ex) {
        return responseMessage.error(500, "服务器异常: " + ex.getMessage());
    }
}
